package cn.xiaomubiao.oschine.fragment.myinfofragment.collection;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import cn.xiaomubiao.oschine.R;
import cn.xiaomubiao.oschine.bean.Post;
import cn.xiaomubiao.oschine.bean.PostDetail;
import cn.xiaomubiao.oschine.contants.Host;
import cn.xiaomubiao.oschine.util.HttpUtil;
import cn.xiaomubiao.oschine.util.OnWebViewImageListener;
import cn.xiaomubiao.oschine.util.StringUtils;
import cn.xiaomubiao.oschine.util.UIHelper;

/**
 * @author
 * @version 1.0
 * @date 2017/4/6
 */

public class MyInfoWebTopicFragment extends Fragment {
    private String body;
    private View mView;
    private WebView mWebView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.view_myinfo_webview,container,false);
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Bundle b = getArguments();
        String idString = b.getString("idString");
        String url = Host.HOST_GENYMOTION+"detail/post_detail/"+idString+".xml";
//        String url = Host.HOST_GENYMOTION+"detail/news_detail/64331.xml";
        mWebView = (WebView) mView.findViewById(R.id.myinfo_webview);

        addWebImageShow(getActivity(),mWebView);

        HttpUtil<PostDetail> httpUtil = new HttpUtil<>(getActivity(),PostDetail.class);
        httpUtil.getStringData(url, new HttpUtil.OnGetDataListener<PostDetail>() {
            @Override
            public void onSuccess(PostDetail blogDetail) {
                Post blog = blogDetail.getPost();
                body = getWebViewBody(blog);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadDataWithBaseURL("", body, "text/html", "UTF-8", "");
                    }
                });
            }

            @Override
            public void onFailure(Exception e) {

            }
        });

    }
    protected String getWebViewBody(Post mDetail) {
        StringBuffer body = new StringBuffer();
        body.append(UIHelper.WEB_STYLE).append(UIHelper.WEB_LOAD_IMAGES);
        // 添加title
        body.append(String.format("<div class='title'>%s</div>", mDetail.getTitle()));
        // 添加作者和时间
        String time = StringUtils.friendly_time(mDetail.getPubDate());
        String author = String.format("<a class='author' href='http://my.oschina.net/u/%s'>%s</a>", mDetail.getAuthorId(), mDetail.getAuthor());
        body.append(String.format("<div class='authortime'>%s&nbsp;&nbsp;&nbsp;&nbsp;%s</div>", author, time));
        // 添加图片点击放大支持
        body.append(setHtmlCotentSupportImagePreview(mDetail.getBody()));
        
//        // 更多关于***软件的信息
//        if (mDetail.getSoftwareName() !=null){
//            String softwareName = mDetail.getSoftwareName();
//            String softwareLink = mDetail.getSoftwareLink();
//            if (!StringUtils.isEmpty(softwareName)
//                    && !StringUtils.isEmpty(softwareLink))
//                body.append(String
//                        .format("<div class='oschina_software' style='margin-top:8px;font-weight:bold'>更多关于:&nbsp;<a href='%s'>%s</a>&nbsp;的详细信息</div>",
//                                softwareLink, softwareName));
//
//        }
//       
//        // 相关新闻
//        if (mDetail != null && mDetail.getRelatives() != null
//                && mDetail.getRelatives().size() > 0) {
//            String strRelative = "";
//            for (News.Relative relative : mDetail.getRelatives()) {
//                strRelative += String.format(
//                        "<li><a href='%s' style='text-decoration:none'>%s</a></li>",
//                        relative.url, relative.title);
//            }
//            body.append("<p/><div style=\"height:1px;width:100%;background:#DADADA;margin-bottom:10px;\"/>"
//                    + String.format("<br/> <b>相关资讯</b><ul class='about'>%s</ul>",
//                    strRelative));
//        }
        body.append("<br/>");
        // 封尾
        body.append("</div></body>");
        return body.toString();
    }

    //所有图片设置点击事件,调用java本地代码
    public static String setHtmlCotentSupportImagePreview(String body) {
        // 读取用户设置：是否加载文章图片--默认有wifi下始终加载图片
        if (true) {
            // 过滤掉 img标签的width,height属性
            body = body.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+", "$1");
            body = body.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+", "$1");
            // 添加点击图片放大支持
            // 添加点击图片放大支持
            body = body.replaceAll("(<img[^>]+src=\")(\\S+)\"",
                    "$1$2\" onClick=\"javascript:mWebViewImageListener.showImagePreview('$2')\"");
        } else {
            // 过滤掉 img标签
            body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>", "");
        }
        return body;
    }

    //js中调用该方法后,启动新的页面展示图片
    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    @JavascriptInterface
    public static void addWebImageShow(final Context cxt, WebView wv) {
        wv.getSettings().setJavaScriptEnabled(true);
        wv.addJavascriptInterface(new OnWebViewImageListener() {
            @Override
            @JavascriptInterface
            public void showImagePreview(String bigImageUrl) {
                if (bigImageUrl != null && !StringUtils.isEmpty(bigImageUrl)) {
                    UIHelper.showImagePreview(cxt, new String[]{bigImageUrl});
                }
            }
        }, "mWebViewImageListener");
    }  
}
